class ArticlesController < ApplicationController
    before_action :authenticate_user!, except: [:index, :show]
    
    # index
    def index
        @articles = Article.all
    end
    
    def show
        @article = Article.find(params[:id])
    end
    
    # New article form
    def new
        @article = current_user.articles.build
    end
    
    # edit
    def edit
        @article = Article.find(params[:id])
    end
    
    # Create an article
    def create
        @article = current_user.articles.build(article_params)
        
        if @article.save then
            redirect_to @article
        else
            render 'new'
        end
    end
    
    # update
    def update
        @article = Article.find(params[:id])
        
        if @article.update(article_params) then
            redirect_to @article
        else
            render 'edit'
        end
    end
    
    # destroy
    def destroy
        @article = Article.find(params[:id])
        @article.destroy
        
        redirect_to articles_path
    end

    private
    def article_params
        params.require(:article).permit(:title, :tag, :summary, :text)
    end
    
end
